<?php

namespace app\api\model;

use app\api\model\Common;

class Speech extends Common
{

    /**
     * 为了数据库的整洁，同时又不影响Model和Controller的名称
     * 我们约定每个模块的数据表都加上相同的前缀，比如微信模块用weixin作为数据表前缀
     */
    protected $name = 'meeting_speech';
    // 定义时间戳字段名,为了关闭时间戳自动转换格式
    protected $createTime = 'create_at';
    protected $updateTime = 'update_at';
    //校验规则
    protected $rules = [];

    /**
     * 绑定user表进行关联查询
     */
    public function users()
    {
        //参数第二个是外键，为本模型的外键字段
        //且在field中必填id字段，否则找不到查询内容
        return $this->belongsTo('User', 'user_id')->field('id,username');
    }

    /**
     * 查询关联user的speech表的文件数据
     */
    public function getDateToUser($start_time, $end_time, $match, $limit, $page, $is_delete = 0)
    {
        // if($GLOBALS['userInfo']['id'] && $GLOBALS['userInfo']['id'] != 1)
        // {
        //     $id = $GLOBALS['userInfo']['id'];
        // }
        //需要查询的字段
        $field = ['m.id', 'formatname', 'filename', 'user_id', 'device_id', 'username', 'm.lvsr_start_time', 'seconds', 'lvsr_status', 'lvsr_data_current'];
        $quary = $id ? 'a.id =' . $id : '';
        try {
            //联表查询
            $list = $this
                ->alias('m')
                ->join('admin_user a', 'm.user_id = a.id', 'LEFT')
                ->where($quary)
                //未被删除的文件
                ->where(['is_delete' => $is_delete])
                //时间戳模糊匹配
                ->where('m.lvsr_start_time', 'between', [$start_time, $end_time])
                //模糊匹配
                ->where('a.username|m.lvsr_start_time', 'like', '%' . $match . '%')
                ->limit($limit)->page($page)->field($field)->order('id desc')
                ->select();
            if ($list) {
                $list = collection($list)->toArray();
                //查询数量
                $count = $this->alias('m')
                    ->join('admin_user a', 'm.user_id = a.id', 'LEFT')
                    ->where($quary)
                    //未被删除的文件
                    ->where(['is_delete' => $is_delete])
                    //时间戳模糊匹配
                    ->where('m.lvsr_start_time', 'between', [$start_time, $end_time])
                    //模糊匹配
                    ->where('a.username|m.lvsr_start_time', 'like', '%' . $match . '%')
                    ->count();
            } else {
                $count = 0;
            }
            return ['list' => $list, 'total' => $count];
        } catch (\Exception $e) {
            throw new \Exception($e->getMessage());
        }
    }

    /**
     * [updateDataById 编辑]
     * @linchuangbin
     * @DateTime  2017-02-10T21:24:49+0800
     * @param     [type]                   $param [description]
     * @param     [type]                   $id    [description]
     * @return    [type]                          [description]
     */
    public function updateDataById($param, $id)
    {
        $checkData = $this->get($id);
        if (!$checkData) {
            $this->error = '暂无此数据';
            return false;
        }

        // 验证
        $validate = validate($this->rules);
        if (!$validate->check($param)) {
            $this->error = $validate->getError();
            return false;
        }
        var_dump('aa');
        try {
            $this->allowField(true)->save($param, [$this->getPk() => $id]);
            return true;
        } catch (\Exception $e) {
            throw new \Exception($e->getMessage());
        }
    }

    /**
     * 删除文件
     */
    public function deletDatas($ids = [])
    {
        try {
            $this->where(['is_delete' => 0])->where($this->getPk(), 'in', $ids)->update(['is_delete' => 1]);
            return true;
        } catch (\Exception $e) {
            throw new \Exception($e->getMessage());
        }
    }

    /**
     * 获取文件数据
     */
    public function getDataByMeetingId($id)
    {
        try {
            if (!$id) {
                $this->error = "查询参数为空";
                return false;
            }
            $map = [
                'meeting_id' => $id,
                'lvsr_status' => 3
            ];
            $data = $this->all($map);
            return $this->offlineTxtMerge($data);
        } catch (\Exception $e) {
            throw new \Exception($e->getMessage());
        }
    }

    //离线文本 合并
    public function offlineTxtMerge($txts)
    {
        $newlist = [];
        $time = 0;
        $consume = 0;
        foreach ($txts as $data_value) {
            $lvsr = isset($data_value['lvsr_data']) ? json_decode($data_value['lvsr_data'], true) : [];
            if ($lvsr === null) {
                continue;
            }
            $consume += $lvsr['consume-time'];
            if (empty($lvsr['list'])) {
                continue;
            }
            foreach ($lvsr['list'] as $key => $time_value) {
                //对文件进行时间的累加
                $time_value_arr = explode("-", $time_value['time']);
                //var_dump($time_value_arr);
                $time_value['time'] = ($time_value_arr[0] + $time) . "-" . ($time_value_arr[1] + $time);
                $newlist[] =  $time_value;
                //如果是最后一个则将$time置为上一段的总时长
                if ($key == count($lvsr['list']) - 1) {
                    $time += $time_value_arr[1];
                }
            }
        }
        $lvsr_data = [
            'consume-time' => $consume,
            'list' => $newlist
        ];
        return json_encode($lvsr_data, JSON_UNESCAPED_UNICODE);
    }
}
